// pages/shop/productDetail/productDetail.js
const app = getApp();
import { list, find } from '../../../api/product'
import { addCart, getCart, update, del as delCart } from "../../../api/cart"
import { add, del,exists } from "../../../api/favorite"
const util = require('../../../utils/util.js')

Page({

        /**
         * 页面的初始数据
         */
        data: {
                productImageUrl: "",
                productName: "香辣鸡腿堡套餐",
                productSales: 100,
                price: 36.0,
                marketPrice: 40.0,
                currentSwiperItem: true,
                swiperCurrent: 0,
                productMoreInfo: [
                        {
                                type: "detail",
                                msg: "详情"
                        },
                        {
                                type: "evaluate",
                                msg: "评价"
                        }
                ],
                productId: "",
                shopId: "",
                productInfo: {}, //商品详情信息
                statusHeight: "",
                navHeight: "",
                quantity:0,
                shoucangSuccessIconUrl:util.thumbnail(app.APP_OSSURL_API+"/dinnerBar/canyin/canyin-yishoucan.png",  48, 48),
                shoucangfailIconUrl:util.thumbnail(app.APP_OSSURL_API+"/dinnerBar/canyin/canyin-weishoucan.png", 48, 48),
                productFavoriteStatus:false, //店铺的收藏状态
                content:"", //富文本的内容

                swiperVideo:"",
                swiperImg:[],
                current:1,
                swiperIndex:0,
        },

        /**
         * 生命周期函数--监听页面加载
         */
        onLoad:function (options){
                let pages = getCurrentPages();
                this.setData({
                        statusBarHeight: app.globalData.statusBarHeight,
                        productId: options.productId,
                        fromShop: pages[pages.length - 2].route=='pages/shop/shopDetail/index'
                        // shopId: options.shopId,
                })  
        },
        onShow: function (options) {
                // let pages = getCurrentPages();
                console.info("商品详情*************")
                console.info(options)
                // this.setData({
                //         statusBarHeight: app.globalData.statusBarHeight,
                //         productId: options.productId,
                //         fromShop: pages[pages.length - 2].route=='pages/shop/shopDetail/index'
                //         // shopId: options.shopId,
                // })
                this.getProductInfo(()=>{
                        console.info("app.globalData.token--"+app.globalData.token)
                        if(app.globalData.token != null){
                                this.getCart()
                                this.selectComponent("#settlement").getCart()
                                this.selectComponent("#settlement").getCount()
                        }
                })
                this.setNavSize()
                if(app.globalData.token != null){
                        this.getProductFavoriteStatus()
                        // this.selectComponent("#settlement").cartHandlerWithoutAnimation()
                }
                
        },

        //检测用户的登陆状态
  checkLogin(callback) {
        console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
        if (app.globalData.token == null) {
          wx.navigateTo({
            url: '/pages/login/index',
          })
        } else {
          if (callback) {
            callback()
          }
        }
      },

        //查询是否收藏店铺
    getProductFavoriteStatus(){
        let params = {
                productId:this.data.productId
        }
        exists(params).then(
            (res)=>{
                if (res.type == 'success') {
                    if(res.data == 1){
                        this.setData({
                            productFavoriteStatus:true
                        })
                    }else{
                        this.setData({
                            productFavoriteStatus:false
                        })
                    }
                }
            }
        ).catch( )
    },

    // 添加店铺收藏
    addProductFavorite(){
            this.checkLogin(()=>{
                if(this.data.productFavoriteStatus){
                        let params = {
                                productId:this.data.productId
                        }
                    del(params).then(
                        (res)=>{
                            if (res.type == 'success') {
                                wx.showToast({
                                    title: "取消收藏成功",
                                    icon:"none"
                                  })
                                  this.setData({
                                    productFavoriteStatus:false
                                })
                            }
                        }
                    ).catch( )
                }else{
                        let data = {
                                productId:this.data.productId,
                                productType: 0
                        }
                    add(data).then(
                        (res)=>{
                            if (res.type == 'success') {
                                wx.showToast({
                                    title: "收藏成功",
                                    icon:"none"
                                  })
                                  this.setData({
                                    productFavoriteStatus:true
                                })
                            }
                        }
                    ).catch( )
                }
            })
    },

        navTo() {
                let p = getCurrentPages().length;
                if (p <= 1) {
                        wx.switchTab({
                                url: '/pages/index/index',
                        })
                } else {
                        wx.navigateBack({
                                delta: 1
                        })
                }
        },

        setNavSize: function () {
                var that = this,
                        sysinfo = wx.getSystemInfoSync(),
                        statusHeight = sysinfo.statusBarHeight,
                        isiOS = sysinfo.system.indexOf('iOS') > -1,
                        navHeight;
                console.log(sysinfo)
                if (!isiOS) {
                        navHeight = 48;
                } else {
                        navHeight = 44;
                }
                that.setData({
                        statusHeight: statusHeight,
                        navHeight: navHeight
                })
        },

        swiperChange(data) {
                var _this = this
                this.data.current = data.detail.current + 1
                this.setData({
                  current: this.data.current
                })
              },

        //获取商品信息
        getProductInfo(callback) {
                let _this = this
                console.info("showAttrDialog---------------")
                find(this.data.productId).then(
                        res => {
                                if (res.type == 'success') {
                                        console.log("我是shopDetail下的getProductInfo--")
                                        console.info(res)
                                        let content = ""
                                        let swiperImg = []
                                        let swiperVideo = ""
                                        let swiperIndex = 0
                                        if (!util.isNull(res.data.content)) {
                                                const regex = new RegExp('<img', 'gi');
                                                content = res.data.content.replace(regex, `<img style="width: 100%;display:block"`);
                                              }
                                        if (!util.isNull(res.data.meta)) {
                                                if (!util.isNull(res.data.meta.images)) {
                                                        swiperImg = res.data.meta.images.map(e=>util.thumbnail(e,750,750));
                                                }
                                                if (!util.isNull(res.data.meta.video)) {
                                                        swiperVideo = res.data.meta.video;
                                                }
                                        }
                                        if (swiperVideo == '') {
                                                swiperIndex = swiperImg.length
                                              } else {
                                                swiperIndex = swiperImg.length + 1
                                              }
                                        let swiperImgNew = []
                                        if(swiperImg.length > 0){
                                                swiperImg.map(item=>{
                                                        swiperImgNew.push(util.thumbnail(item, 750, 750))
                                                })
                                        }
                                        this.setData({
                                                swiperImg:swiperImgNew,
                                                swiperVideo:swiperVideo,
                                                swiperIndex:swiperIndex,
                                                productInfo: res.data.products[0],
                                                content:content,
                                                shopId:res.data.shopId
                                        })
                                        if(callback){
                                                callback(res.data)
                                        }
                                }
                        }
                ).catch(error => { })
        },

        //获取购物车信息
        getCart(callback) {
                let params = {
                        shopId: this.data.shopId,
                        uuid: app.globalData.uuid
                }
                getCart(params).then(
                        res => {
                                console.log("我是shopDetail下的getCart--")
                                console.log(res)
                                if (res.type == 'success') {
                                        if(res.data.cart.itemVoList.length > 0){
                                                let clearOff= true
                                                let quantity = 0
                                                res.data.cart.itemVoList.map(item => {
                                                        if(item.goodsId == this.data.productInfo.goodsId){
                                                                quantity += item.quantity
                                                                // clearOff = false   
                                                        }
                                                })
                                                // if(clearOff){
                                                //         this.setData({
                                                //                 quantity : 0
                                                //         })
                                                // }
                                                this.setData({
                                                        cartInfo: res.data.cart,
                                                        quantity:quantity
                                                })
                                        }else{
                                                this.setData({
                                                        cartInfo: res.data.cart,
                                                        quantity:0
                                                })      
                                        }
                                        
                                        console.log("quantity---------"+this.data.quantity)
                                        if (callback) {
                                                callback(res.data)
                                        }
                                }
                        }
                ).catch(error => { })
        },

        //空状态情况下加购物车
        addCartNone(e){

        },

        //购物车减操作
        reduceCart(e){
                console.info(e)
                let _this = this
                let maxLimit = e.currentTarget.dataset.item.maxLimit
                let minLimit = e.currentTarget.dataset.item.minLimit>1?e.currentTarget.dataset.item.minLimit:1
                let cartId = ""
                let sendData = {
                        type:"reduce",
                        shopId: _this.data.shopId, 
                        clientX: e.touches[0].clientX,
                        clientY: e.touches[0].clientY
                }
                if(_this.data.quantity > 0){
                        if(_this.data.cartInfo.itemVoList.length > 0){
                                _this.data.cartInfo.itemVoList.map(item => {
                                        if(item.productId == e.currentTarget.dataset.item.id){
                                                cartId = item.id
                                        }
                                })
                        }
                        if(_this.data.quantity > minLimit){
                                let data = [{
                                        id:cartId,
                                        quantity:_this.data.quantity - 1,
                                        chk : true
                                }]
                                update(data).then(
                                        res => {
                                        //   console.log("addCart--" + JSON.stringify(res))
                                          if (res.type == 'success') {
                                                _this.getCart()
                                                _this.selectComponent("#settlement").cartHandlerWithoutAnimation()
                                            }
                                        }
                                      ).catch(error => {})
                        }else{
                                let delIds = [cartId]
                                delCart(delIds).then(
                                                res => {
                                                  // console.log("我是组件的getCart--" + JSON.stringify(res))
                                                  if (res.type == 'success') {
                                                        _this.getCart()
                                                        _this.selectComponent("#settlement").cartHandlerWithoutAnimation()
                                                  }
                                                }
                                              ).catch(error => {})
                        }
                        
                }
        },

        //购物车加操作
        addCart(e){
                let _this = this
                console.info(e)
                let maxLimit = e.currentTarget.dataset.item.maxLimit
                        let minLimit = e.currentTarget.dataset.item.minLimit
                        if(maxLimit == _this.data.quantity&&maxLimit>0){
                                wx:wx.showToast({
                                  title: `该菜品限购${maxLimit}件哦！`,
                                  duration: 2000,
                                  icon: "none",
                                })
                        }else{
                        let sendData = {
                                productId: _this.data.productId,
                                type:"add",
                                shopId: _this.data.shopId, 
                                clientX: e.touches[0].clientX,
                                clientY: e.touches[0].clientY
                        }
                        if(e.currentTarget.dataset.item.sku > 1){
                                console.info("e.currentTarget.dataset.item.sku --"+e.currentTarget.dataset.item.sku )
                                this.selectComponent("#attributeDialog").showAttrDialog(sendData, this.data.cartInfo)
                        }else {
                                let params = {
                                        productId:e.currentTarget.dataset.item.id,
                                        quantity:1,
                                        shopId:_this.data.shopId,
                                        uuid: app.globalData.uuid
                                }
                                if(_this.data.quantity < minLimit){
                                        params.quantity = minLimit
                                        if(minLimit>1){
                                                wx.showToast({
                                                        title: `该菜品${minLimit}件起购哦！`,
                                                        duration: 2000,
                                                        icon: "none",
                                                      })
                                        }
                                                 
                                }else{
                                        params.quantity = 1
                                }
                                addCart(params).then(
                                        res => {
                                        //   console.log("addCart--" + JSON.stringify(res))
                                          if (res.type == 'success') {
                                                _this.getCart()
                                                _this.selectComponent("#settlement").cartHandler(sendData)
                                                // _this.triggerEvent('reloadCart', sendData)
                                            }
                                        }
                                      ).catch(error => {})
                        }
                }
        },

        //属性选择框加购的回叫信息
        reloadCartFromAttr(){
             this.getCart() 
             this.selectComponent("#settlement").cartHandlerWithoutAnimation()  
        },

        //点击详情和评价切换
        swiperChange(e) {
                console.info(e)
                e.currentTarget.dataset.type
                if (this.data.productMoreInfo.length > 0) {
                        if (e.currentTarget.dataset.type == "detail") {
                                this.setData({
                                        currentSwiperItem: true, swiperCurrent: 0
                                })
                        } else {
                                this.setData({
                                        currentSwiperItem: false, swiperCurrent: 1
                                })
                        }
                }
        },

        //点击切换滑块
        bindchange(e) {
                console.info("点击切换滑块")
                console.info(e)
                e.detail.current
                if (e.detail.current == 0) {
                        this.setData({
                                currentSwiperItem: true
                        })
                } else {
                        this.setData({
                                currentSwiperItem: false
                        })
                }
        },

        //切换滑块触发事件
        bindtransition(e) {
                // console.info("切换滑块触发事件")
                // console.info(e)
        },

        toShop(){
                if(!this.data.shopId){
                        wx.showToast({
                          title: '未找到对应商家',
                          icon:'none'
                        })
                        return
                }
                wx.navigateTo({
                  url: `/pages/shop/shopDetail/index?shopId=${this.data.shopId}`,
                })
        }

})